﻿using FreeSql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.DBCommon
{
    /// <summary>
    /// 获取Freesql对象及添加数据对象
    /// </summary>
    public static class FreesqlFactory
    {
        private static Dictionary<string, IFreeSql> freesqlMo = new Dictionary<string, IFreeSql>();
        /// <summary>
        /// 根据数据库的code返回数据库操作对象
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public static IFreeSql GetFreeSql(string dbcode)
        {
            bool result = freesqlMo.TryGetValue(dbcode.ToLower(), out IFreeSql freeSql);
            if (result)
                return freeSql;
            return null;
        }

        /// <summary>
        /// 添加数据连接
        /// </summary>
        /// <param name="conStr"></param>
        /// <param name="bdcode"></param>
        /// <param name="sqltype"></param>
        public static void CreatFreeSql(string conStr, string bdcode, string sqltype)
        {
            IFreeSql freeSql = null;
            FreeSqlBuilder freeSqlBuilder = null;
            switch (sqltype.ToLower())
            {
                case "mysql":
                    freeSqlBuilder = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, conStr);
                    break;
                case "sqlserver":
                    freeSqlBuilder = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.SqlServer, conStr);
                    break;
                case "dmserver":
                    freeSqlBuilder = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.Dameng, conStr);
                    break;
                case "sqlite":
                    freeSqlBuilder = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.Sqlite, conStr);
                    break;
                case "oracle":
                    freeSqlBuilder = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.Oracle, conStr);
                    break;
                default:
                    break;
            }
            freeSql = freeSqlBuilder.UseMonitorCommand(cmd =>
            {
                //    logger?.LogInformation(cmd.CommandText);
            }, //监听SQL命令对象，在执行前
                            (cmd, traceLog) =>
                            {
                                Console.WriteLine(traceLog);
                            }).Build();
            if (freeSql != null)
                freesqlMo.Add(bdcode.ToLower(), freeSql);
        }
    }
}
